#include "c_mainwindow.h"
#include "ui_c_mainwindow.h"

#define _(x) QString::fromUtf8(x)

#include <QCloseEvent>
#include <QProgressBar>
#include <QMessageBox>
#include <QFileDialog>
#include <QItemDelegate>
#include <QTableView>

#include "../logger/Logger.h"
#include "../filehandling/FileType.h"

using namespace Common;
using namespace Logger;

namespace Client {

MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent), ui(new Ui::MainWindowClass)
{
	QTimer timer(this);
	QFile config(".config");
	config.open(QFile::ReadOnly);
	QByteArray ba = config.readLine(100);
	QString ip(ba);
	config.close();

	ui->setupUi(this);

	lblServerStatus = new QLabel;
	lblServerStatus->setText("Status serwera");
	ui->statusBar->addPermanentWidget(lblServerStatus);

	QProgressBar * progressBar = new QProgressBar(this);
	progressBar->setValue(17);
	ui->statusBar->addPermanentWidget(progressBar);

	connect(&timer, SIGNAL(timeout()), ui->treeJobs, SLOT(reset()));

	timer.start(1000);

#ifndef NO_CONTROLLER
	connect(&controller, SIGNAL(serverConnected()), this, SLOT(onControllerServerState()));
	connect(&controller, SIGNAL(serverDisconnected()), this, SLOT(onControllerServerState()));
	connect(&controller, SIGNAL(updateSearchResult()), this, SLOT(onUpdateSearchResult()));

	/*Log & log(Log::get());
	log.addOutput(new OutputText("client_log.txt"));

	connect(&controller, SIGNAL(newMsg(QString, int)), &log, SLOT(onNewMessage(const QString &, int)));*/


	controller.start(ip);

	if (controller.mainServer())
		lblServerStatus->setText(QString("Serwer: ") + controller.mainServer()->getAddr());

	ui->treeShared->setModel(controller.getSharedFilesModel());
	ui->treeShared->setRootIsDecorated(false);

	ui->treeSearch->setModel(controller.getSearchResultModel());
	ui->treeSearch->setRootIsDecorated(false);

	ui->treeJobs->setModel(controller.getJobsModel());
	ui->treeJobs->setRootIsDecorated(false);
#endif

}

MainWindow::~MainWindow()
{
	delete ui;
}

void MainWindow::on_btnTransfers_clicked(bool checked)
{
	if (checked) {
		ui->LeftPanelGroup->setCurrentIndex(0);
		ui->MainPanelGroup->setCurrentIndex(0);
	}
}

void MainWindow::on_btnDownloaded_clicked(bool checked)
{
	if (checked) {
		ui->LeftPanelGroup->setCurrentIndex(1);
		ui->MainPanelGroup->setCurrentIndex(1);
	}
}

void MainWindow::on_btnUploads_clicked(bool checked)
{
	if (checked) {
		ui->LeftPanelGroup->setCurrentIndex(2);
		ui->MainPanelGroup->setCurrentIndex(2);
	}
}

void MainWindow::on_btnSearch_clicked(bool checked)
{
	if (checked) {
		ui->LeftPanelGroup->setCurrentIndex(3);
		ui->MainPanelGroup->setCurrentIndex(3);
	}
}

void MainWindow::on_btnConfig_clicked(bool checked)
{
	if (checked) {
		ui->LeftPanelGroup->setCurrentIndex(4);
		ui->MainPanelGroup->setCurrentIndex(4);
	}
}

void MainWindow::on_btnAbout_clicked(bool checked)
{
	if (checked) {
		ui->LeftPanelGroup->setCurrentIndex(5);
		ui->MainPanelGroup->setCurrentIndex(5);
	}
}

void MainWindow::closeEvent(QCloseEvent *event) {
#ifndef NO_CONTROLLER
	controller.stop();
#endif
	event->accept();
}

bool MainWindow::checkConnection() {
#ifndef NO_CONTROLLER
	if (controller.mainServer() == NULL) {
		QMessageBox::information(this, _("Brak połączenia"), _("Brak połączenia z serwerem. Operacja nie może być wykonana."));
		return false;
	} else {
		return true;
	}
#else
	return false;
#endif
}

void MainWindow::onControllerServerState() {
#ifndef NO_CONTROLLER
	if (controller.mainServer())
		lblServerStatus->setText(QString("Serwer: ") + controller.mainServer()->getAddr());
#endif
}


void MainWindow::on_btnStartSearch_clicked()
{
	if (!checkConnection())
		return;

	int file_size[] = {       -1,
							1024,      1024*10,      1024*100,
					   1024*1024, 1024*1024*10, 1024*1024*100,
				  1024*1024*1024 };

	FileType file_type[] = {ftAny, ftAudio, ftMovie, ftDoc, ftArchive, ftPicture, ftIso, ftEbook, ftSoftware, ftGame};

	QString query = ui->editQuery->text();
	int min_size = -1;
	int max_size = -1;

	FileType type = ftAny;

	if (ui->btnExtendedSearch->isChecked()) {
		min_size = file_size[ui->cbSearchFrom->currentIndex()];
		max_size = file_size[ui->cbSearchTo->currentIndex()];
		type = file_type[ui->cbSearchType->currentIndex()];

	}
#ifndef NO_CONTROLLER
	controller.find(query, type, min_size, max_size);
#endif
}

void MainWindow::on_btnAddSharedFile_clicked()
{
	QFileDialog::Options options;
//	if (!native->isChecked())
		options |= QFileDialog::DontUseNativeDialog;

	QString selectedFilter;
	QString openFilesPath;
	QStringList files = QFileDialog::getOpenFileNames(
			this,
			tr("QFileDialog::getOpenFileNames()"),
			".",
			tr("All Files (*)"),
			&selectedFilter,
			options);

	if (files.count()) {
		foreach (QString fname, files) {
			ui->lblSharedInfo->setText(fname);
#ifndef NO_CONTROLLER
			controller.addSharedFile(fname);
#endif
			//std::cout << fname.toStdString() << "\n";
		}
		std::cout.flush();
	}
	ui->lblSharedInfo->setText("");
	ui->treeShared->reset();

#ifndef NO_CONTROLLER
	controller.sendAddedFiles();
#endif
}

void MainWindow::onUpdateSearchResult() {
	ui->treeSearch->reset();
}

void MainWindow::on_treeSearch_doubleClicked(QModelIndex index)
{

#ifndef NO_CONTROLLER
	FileDesc * file = static_cast<FileDesc*>(index.internalPointer());
	controller.download(file);
	ui->treeJobs->reset();
#endif

}

} // namespace Client
